#!/usr/bin/python
# -*- coding: UTF-8 -*-

import urllib2
import time
import urllib
import json
import hashlib
import base64
import sys;sys.path.append('../')
import Config as C


"""
function: 借用科大讯飞的语音识别API将wav文件内容转化成文字信息
parameter: filename 用户语音文件路径
return: 转化成功后的文字信息
"""
def speechRecognition(filename):
    try:
        f = open(filename, 'rb')
        file_content = f.read()
    except:
        #print('文件读取出错啦')
        #sys.exit()
        return " "
    base64_audio = base64.b64encode(file_content)
    body = urllib.urlencode({'audio': base64_audio})
    
    url = 'http://api.xfyun.cn/v1/service/v1/iat'
    api_key = C.sR_API_KEY
    param = {"engine_type": "sms16k", "aue": "raw"}
    
    x_appid = C.sR_APPID
    x_param = base64.b64encode(json.dumps(param).replace(' ', ''))
    x_time = int(int(round(time.time() * 1000)) / 1000)
    x_checksum = hashlib.md5(api_key + str(x_time) + x_param).hexdigest()
    x_header = {'X-Appid': x_appid,
                'X-CurTime': x_time,
                'X-Param': x_param,
                'X-CheckSum': x_checksum}
    
    req = urllib2.Request(url, body, x_header)
    result = urllib2.urlopen(req)
    result = result.read()
    resultList = result.split(',')
    
    return str(resultList[1])[8:-1]

#a = speechRecognition('say_voice.wav')
#print a.decode('UTF-8').encode('GBK')
